package com.ruoyi.biz.service.impl;

import com.alibaba.fastjson.JSON;
import com.ruoyi.biz.domain.*;
import com.ruoyi.biz.mapper.BizCourseCreditMapper;
import com.ruoyi.biz.mapper.BizCourseExamMapper;
import com.ruoyi.biz.mapper.BizCourseExamScoreMapper;
import com.ruoyi.biz.mapper.BizCourseMapper;
import com.ruoyi.biz.service.IBizCourseCreditService;
import com.ruoyi.biz.service.IBizCourseDetailService;
import com.ruoyi.biz.service.IBizCourseExamService;
import com.ruoyi.biz.service.IBizCourseService;
import com.ruoyi.common.core.domain.Ztree;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * 课程考试题Service业务层处理
 *
 * @author ruoyi
 * @date 2021-08-24
 */
@Service
public class BizCourseExamServiceImpl implements IBizCourseExamService {

    protected final Logger log = LoggerFactory.getLogger(BizCourseExamServiceImpl.class);

    @Autowired
    private BizCourseExamMapper bizCourseExamMapper;

    @Autowired
    BizCourseDetailServiceImpl courseDetailService;

    @Autowired
    private BizCourseExamScoreMapper examScoreMapper;

    @Autowired
    private IBizCourseDetailService detailService;

    @Autowired
    private IBizCourseCreditService courseCreditService;

    @Autowired
    private IBizCourseService bizCourseService;

    /**
     * 查询课程考试题
     *
     * @param id 课程考试题ID
     * @return 课程考试题
     */
    @Override
    public BizCourseExam selectBizCourseExamById(Long id) {
        return bizCourseExamMapper.selectBizCourseExamById(id);
    }

    /**
     * 查询课程考试题列表
     *
     * @param bizCourseExam 课程考试题
     * @return 课程考试题
     */
    @Override
    public List<BizCourseExam> selectBizCourseExamList(BizCourseExam bizCourseExam) {
        return bizCourseExamMapper.selectBizCourseExamList(bizCourseExam);
    }

    /**
     * 新增课程考试题
     *
     * @param bizCourseExam 课程考试题
     * @return 结果
     */
    @Override
    public int insertBizCourseExam(BizCourseExam bizCourseExam) {
        bizCourseExam.setCreateTime(DateUtils.getNowDate());
        return bizCourseExamMapper.insertBizCourseExam(bizCourseExam);
    }

    /**
     * 修改课程考试题
     *
     * @param bizCourseExam 课程考试题
     * @return 结果
     */
    @Override
    public int updateBizCourseExam(BizCourseExam bizCourseExam) {
        bizCourseExam.setUpdateTime(DateUtils.getNowDate());
        return bizCourseExamMapper.updateBizCourseExam(bizCourseExam);
    }

    /**
     * 删除课程考试题对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteBizCourseExamByIds(String ids) {
        return bizCourseExamMapper.deleteBizCourseExamByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除课程考试题信息
     *
     * @param id 课程考试题ID
     * @return 结果
     */
    @Override
    public int deleteBizCourseExamById(Long id) {
        return bizCourseExamMapper.deleteBizCourseExamById(id);
    }

    @Override
    public List<Ztree> selectCourseTree() {
        List<Ztree> ztrees = courseDetailService.selectCourseTree();

        List<BizCourseDetail> BizCourseDetails = courseDetailService.selectBizCourseDetailList(new BizCourseDetail());
        for (BizCourseDetail c : BizCourseDetails) {
            Ztree ztree = new Ztree();
            ztree.setId(c.getId() - 100000); // 四级-10w 防止冲突
            ztree.setpId(c.getCourseId() - 10000);
            ztree.setName(c.getTitle());
            ztree.setTitle(c.getTitle());
            ztrees.add(ztree);
        }

        return ztrees;
    }

    @Override
    public Map checkAnswer(long id, String answers, Long userId) {
        HashMap<String, Object> result = new HashMap<>();
        List<String> errorQueryList = new ArrayList<>();
        result.put("errorQueryList", errorQueryList);

        BizCourseExam bizCourseExam = bizCourseExamMapper.selectBizCourseExamById(id);
        String        examContent   = bizCourseExam.getExamContent();
        List           list           = JSON.parseObject(examContent, List.class);
        log.info(list.toString());
        Map answerMap = JSON.parseObject(answers);

        for (int i = 0; i < list.size(); i++) {
            Map query = (Map) list.get(i);
            String title = (String) query.get("_title");
            String answer = (String) query.get("answer");
            Integer score = (Integer) query.get("_ceshiValue");
            String userAnswer = (String) answerMap.get(String.valueOf(i+1));

            log.info(">>>>answer={},userAnswer={}",answer,userAnswer);
            if (!answer.equalsIgnoreCase(userAnswer)) {
                errorQueryList.add(title);
            }else{
                recordExamInfo(userId,bizCourseExam);
            }
        }
        if (CollectionUtils.isEmpty(errorQueryList)) {
            result.put("passed", 1);
        }else{
            result.put("passed", -1);
        }
        return result;
    }

    private void recordExamInfo(Long userId, BizCourseExam bizCourseExam) {
        Long courseDetailId = bizCourseExam.getCourseDetailId();
        Long id             = bizCourseExam.getId();
        BizCourseExamScore examScore = new BizCourseExamScore();
        examScore.setExamId(id.intValue());
        examScore.setCourseDetailId(courseDetailId.intValue());
        examScore.setPassed(1);
        examScore.setUserId(userId.intValue());
        examScore.setCreateTime(new Date());
        examScoreMapper.insertBizCourseExamScore(examScore);

        BizCourseDetail courseDetail = courseDetailService.selectBizCourseDetailById(courseDetailId);

        Long            courseId     = courseDetail.getCourseId();
        HashMap<String, Object> param = new HashMap<>();
        param.put("userId", userId);
        param.put("courseId", courseId);
        List<BizCourseDetail> list = detailService.selectBizCourseDetailListWihtUserInfo(param);
        int passCourse = 1;
        for (int i = 0; i < list.size(); i++) {
            BizCourseDetail d = list.get(0);
            int             passed = d.getPassed();
            passCourse = passCourse & passed;
        }
        if (passCourse == 1) {
            // 课程考试全部通过,获得学分
            BizCourse course = bizCourseService.selectBizCourseById(courseId);
            log.info(">>>>>考试全部通过,获得学分:{},{}",course.getCourseName(),course.getCourseScore());
            Float     courseScore = course.getCourseScore();

            BizCourseCredit courseCredit = new BizCourseCredit();
            courseCredit.setUserId(userId.intValue());
            courseCredit.setCourseCredit(courseScore);
            courseCredit.setCourseId(courseId.intValue());
            courseCredit.setCreateTime(new Date());
            courseCreditService.insertBizCourseCredit(courseCredit);
        }

    }
}
